<template>
  <div>
    <div class="flex-between mb-16">
      <h2>套餐功能对照表</h2>
      <a-button type="primary" @click="handleAdd">
        <PlusOutlined />
        新建功能对照
      </a-button>
    </div>

    <a-alert
      message="重要说明"
      type="info"
      show-icon
      closable
      style="margin-bottom: 16px;"
    >
      <template #description>
        <div>
          <p><strong>各版本对应关系（按套餐类型匹配）：</strong></p>
          <ul style="margin: 8px 0; padding-left: 20px;">
            <li><strong>基础版</strong> = 技术服务套餐中"套餐类型"为"基础版"的套餐</li>
            <li><strong>标准版</strong> = 技术服务套餐中"套餐类型"为"标准版"的套餐</li>
            <li><strong>专业版</strong> = 技术服务套餐中"套餐类型"为"专业版"的套餐</li>
            <li><strong>企业版</strong> = 技术服务套餐中"套餐类型"为"企业版"的套餐</li>
          </ul>
          <p style="margin-top: 8px; color: #ff4d4f;">
            <strong>⚠️ 重要：</strong>请先在"技术服务套餐"中为每个套餐选择正确的"套餐类型"（下拉选择），功能对照表会自动按类型匹配！
          </p>
          <p style="margin-top: 8px;"><strong>填写建议：</strong></p>
          <ul style="margin: 8px 0; padding-left: 20px;">
            <li>支持的功能填写：<code>√</code> 或 <code>✓</code> → 显示为绿色✅</li>
            <li>不支持的功能填写：<code>×</code> 或 <code>✗</code> → 显示为红色❌</li>
            <li>限制数量的填写具体值：如 <code>5GB</code>、<code>10个</code>、<code>7x24小时</code></li>
            <li>不限制的填写：<code>不限</code> 或 <code>无限</code></li>
          </ul>
        </div>
      </template>
    </a-alert>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      row-key="id"
      :scroll="{ x: 1200 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'green' : 'default'">
            {{ record.status === 1 ? '显示' : '隐藏' }}
          </a-tag>
        </template>
        <template v-else-if="['basic_plan', 'standard_plan', 'professional_plan', 'enterprise_plan'].includes(column.key)">
          <span :style="{ color: getSupportColor(record[column.key]) }">
            {{ formatSupportText(record[column.key]) }}
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定删除这个功能对照吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新建/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="900px"
    >
      <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="功能名称" required>
          <a-input v-model:value="formState.feature_name" placeholder="请输入功能名称" />
        </a-form-item>
        
        <a-form-item label="功能分类">
          <a-input v-model:value="formState.feature_category" placeholder="例如：基础功能、高级功能、增值服务" />
        </a-form-item>
        
        <a-form-item label="功能描述">
          <a-textarea v-model:value="formState.description" :rows="2" placeholder="请输入功能描述" />
        </a-form-item>

        <a-divider orientation="left">各版本支持情况</a-divider>
        
        <a-form-item label="基础版" help="例如：√、×、5GB、10个">
          <a-input v-model:value="formState.basic_plan" placeholder="支持情况或限制" />
        </a-form-item>
        
        <a-form-item label="标准版" help="例如：√、×、20GB、50个">
          <a-input v-model:value="formState.standard_plan" placeholder="支持情况或限制" />
        </a-form-item>
        
        <a-form-item label="专业版" help="例如：√、×、100GB、不限">
          <a-input v-model:value="formState.professional_plan" placeholder="支持情况或限制" />
        </a-form-item>
        
        <a-form-item label="企业版" help="例如：√、×、不限、定制">
          <a-input v-model:value="formState.enterprise_plan" placeholder="支持情况或限制" />
        </a-form-item>

        <a-divider />
        
        <a-form-item label="排序">
          <a-input-number v-model:value="formState.sort_order" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item label="状态">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">显示</a-radio>
            <a-radio :value="0">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getPackageFeatures, createPackageFeature, updatePackageFeature, deletePackageFeature } from '@/api/package'
import type { PackageFeature } from '@/types'

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 60, fixed: 'left' },
  { title: '功能名称', dataIndex: 'feature_name', key: 'feature_name', width: 180, fixed: 'left' },
  { title: '功能分类', dataIndex: 'feature_category', key: 'feature_category', width: 120 },
  { title: '基础版', dataIndex: 'basic_plan', key: 'basic_plan', width: 120, align: 'center' },
  { title: '标准版', dataIndex: 'standard_plan', key: 'standard_plan', width: 120, align: 'center' },
  { title: '专业版', dataIndex: 'professional_plan', key: 'professional_plan', width: 120, align: 'center' },
  { title: '企业版', dataIndex: 'enterprise_plan', key: 'enterprise_plan', width: 120, align: 'center' },
  { title: '排序', dataIndex: 'sort_order', key: 'sort_order', width: 80 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
]

const dataSource = ref<PackageFeature[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

const modalVisible = ref(false)
const modalTitle = ref('新建功能对照')
const editId = ref<number>()

const formState = reactive<Partial<PackageFeature>>({
  feature_name: '',
  feature_category: '',
  description: '',
  basic_plan: '',
  standard_plan: '',
  professional_plan: '',
  enterprise_plan: '',
  sort_order: 0,
  status: 1
})

// 格式化支持文本
const formatSupportText = (value: string | undefined) => {
  if (!value) return '-'
  if (value === '√' || value === '✓' || value.toLowerCase() === 'yes') return '✓'
  if (value === '×' || value.toLowerCase() === 'no') return '×'
  return value
}

// 获取支持状态颜色
const getSupportColor = (value: string | undefined) => {
  if (!value) return '#999'
  const formatted = formatSupportText(value)
  if (formatted === '✓') return '#52c41a'
  if (formatted === '×') return '#ff4d4f'
  return '#1890ff'
}

const fetchFeatures = async () => {
  loading.value = true
  try {
    const res = await getPackageFeatures({
      page: pagination.current,
      page_size: pagination.pageSize
    })
    dataSource.value = res.data.items
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取功能对照列表失败', error)
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchFeatures()
}

const handleAdd = () => {
  modalTitle.value = '新建功能对照'
  editId.value = undefined
  Object.assign(formState, {
    feature_name: '',
    feature_category: '',
    description: '',
    basic_plan: '',
    standard_plan: '',
    professional_plan: '',
    enterprise_plan: '',
    sort_order: 0,
    status: 1
  })
  modalVisible.value = true
}

const handleEdit = (record: PackageFeature) => {
  modalTitle.value = '编辑功能对照'
  editId.value = record.id
  Object.assign(formState, {
    feature_name: record.feature_name,
    feature_category: record.feature_category,
    description: record.description,
    basic_plan: record.basic_plan,
    standard_plan: record.standard_plan,
    professional_plan: record.professional_plan,
    enterprise_plan: record.enterprise_plan,
    sort_order: record.sort_order,
    status: record.status
  })
  modalVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (editId.value) {
      await updatePackageFeature(editId.value, formState)
      message.success('更新成功')
    } else {
      await createPackageFeature(formState)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchFeatures()
  } catch (error) {
    console.error('提交失败', error)
    message.error('操作失败，请重试')
  }
}

const handleCancel = () => {
  modalVisible.value = false
}

const handleDelete = async (id: number) => {
  try {
    await deletePackageFeature(id)
    message.success('删除成功')
    fetchFeatures()
  } catch (error) {
    console.error('删除失败', error)
    message.error('删除失败，请重试')
  }
}

onMounted(() => {
  fetchFeatures()
})
</script>

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb-16 {
  margin-bottom: 16px;
}
</style>

